package controllers;



import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.jayway.jsonpath.JsonPath;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Searchable;

import models.edu_courses;
import models.edu_institutions;
import models.edu_instructors;
import models.edu_tags;
import models.edu_tagscourses;

import play.Play;
import play.api.Logger;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import search.ISearchable;
import search.SearchResult;
import search.SearchUtils;
import search.SearchableIndexer;
import search.Searcher;
import search.FoundItem;
import views.html.*;
import views.html.defaultpages.error;

public class SearchOperations extends Controller {
	private static String indexPath = Play.application().path().getAbsolutePath() + "/indexDir";
	
	
	public static void addCourseToIndex(ISearchable searchable,String tags) throws IOException, ParseException{
		SearchableIndexer indexer = new SearchableIndexer(indexPath);
		indexer.addSearchable(searchable, tags);
		indexer.create();
	}
	
	public static void updateCourseTagsInIndex(int searchableId,String tags) throws IOException, ParseException{
		SearchableIndexer indexer = new SearchableIndexer(indexPath);
		indexer.updateSearchableTags(searchableId, tags);
		indexer.create();
	} 
	
	public static Result search(String query) throws CorruptIndexException, IOException, ParseException{
		Searcher searcher = new Searcher(indexPath);
		SearchResult result= searcher.search(query.trim().replace('_', ' ').replace('/', ' '), 1);
		return ok(Json.toJson(result.getHits())); 
	}
	
	
	
	public static Result fetchQueryItems(String query) throws IOException{
	  return ok(SearchUtils.fetchQueryItemsResult(query));
	}
}
